import React, {Component} from 'react';
import moment from 'moment'
import {Upload as AntdUpload, Button, Select} from 'antd';
// import PropTypes from 'prop-types';
import UploadView from "./UploadView";

const {Option} = Select;

const UploadState = {
  WAITING:'waiting',
  UPLOADED:'uploaded',
}

class Upload extends Component {
  constructor(props) {
    super(props);
    // 存放删除的任务
    this.removeTask=[];
    this.cateId = {};
    this.baseId = 0;
  }
  state = {
    fileList: [],
    canUpload: false,
    error:false,
  }
  componentWillMount(){
    const {defaultValue=[],value=[]} = this.props;
    if(defaultValue.length) {
      this.setState({fileList:defaultValue});
    }
    if(value.length) {
      this.setState({fileList:value});
    }
  }
  onChange = (fileList) => {
    const {onChange} = this.props;
    if(onChange){
      const uploadTask = fileList.filter(item=>item.status === UploadState.WAITING);
      onChange(fileList, uploadTask, this.removeTask);
    }
  }
  onCateChange = (value) => {
    const canUpload = true;
    this.setState({fileCate: value, canUpload,error:false});
  }
  getThumb = (file) => {
    const reader = new FileReader();
    return new Promise((resolve, reject) => {
      reader.readAsDataURL(file);
      reader.onload = () => {
        resolve(reader.result);
      }
      reader.onerror = (e) => {
        reject(e);
      }
    });
  }
  getCateId = (fileCate) => {
    const cid = this.cateId[fileCate];
    if (!cid) {
      this.cateId[fileCate] = 0;
    }
    return (++this.cateId[fileCate]);
  }
  getAlias = (file) => {
    const {fileCate} = this.state;
    const cid = this.getCateId(fileCate);
    const {name} = file;
    const dotIndex = name.lastIndexOf('.')
    let fileName = `${fileCate}-${moment(Date.now()).format('YYYYMMDDHHmmss')}-${cid}`;
    if (dotIndex !== -1) {
      fileName = `${fileName}${name.substr(dotIndex)}`;
    }
    return fileName;
  }
  fileExist = (file) => {
    const {size, name, lastModified} = file;
    const {fileList} = this.state;
    return fileList.findIndex(item => item.size === size && item.name === name && item.lastModified === lastModified) !== -1;
  }
  handleUploadChange = (fileInfo) => {
    const {file} = fileInfo;
    if (!this.fileExist(file)) {
      const {fileList, fileCate} = this.state;
      const {size, name, lastModified} = file;
      const newFile = this.packFile(file, {
        id: (this.baseId++),
        cate: fileCate,
        size,
        name,
        alias: this.getAlias(file),
        lastModified,
        thumb: null,
        status:UploadState.WAITING,
      });
      fileList.push(newFile);
      if (/image/.test(file.type)) {
        this.getThumb(file).then(result => {
          const index = fileList.findIndex(item => item.id === newFile.id);
          if (index !== -1) {
            fileList[index].thumb = {type: 'image', data: result};
            this.setState({fileList},()=>{
              this.onChange(fileList);
            })
          }
        })
      }
      this.setState({fileList},()=>{
        this.onChange(fileList);
      })
    }
  };
  handleClick =() => {
    if(!this.state.canUpload) {
      this.setState({error:true});
    }
  }
  handleDelete = (record) => {
    const fileList = this.state.fileList.filter(item => item.id !== record.id);
    this.setState({fileList}, () => {
      this.onChange(fileList);
      if(record.status === UploadState.UPLOADED) {
          this.removeTask.push(record);
      }
    });
  }
  packFile = (file, props) => {
    return {file, ...props};
  }
  render() {
    const disabled = 'disabled' in this.props && this.props.disabled;
    const {fileList, error} = this.state;
    const {tagList=[], currentData=[]} = this.props;
    const useTagList = tagList.length ? tagList : currentData;
    const uploadProps = {
      beforeUpload: () => {
        return false;
      },
      fileList,
      showUploadList: false,
      multiple: true,
      onChange: this.handleUploadChange,
      disabled: disabled || !this.state.canUpload,
    };

    return (
      <div>
        <div>
          <Select style={{width: 150}} value={this.state.fileCate} onChange={this.onCateChange} placeholder='选择附件类别'>
            {useTagList.map(item=><Option key={item.text}>{item.text}</Option>)}
          </Select>
          <AntdUpload {...uploadProps} webkitdirectory={false}>
            <Button style={{width: 80, padding: '0 10px'}} onClick={this.handleClick}>
              选择文件
            </Button>
          </AntdUpload>
        </div>
        {error && (
          <div style={{color:'#f00'}}>
            你还没有选择附件类别
          </div>
        )}
        <div style={{margin:'10px 0'}}>
          <UploadView dataSource={this.state.fileList} onDelete={this.handleDelete} />
        </div>
      </div>
    );
  }
}

Upload.propTypes = {};
export default Upload;
